import time

from django.db.models import Q
from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView

from cart.models import CartModel
from order.models import OrderModel, DetailModel, MyGoodsModel
from order.orderser import OrderSerializer, DetailSerializer, MyGoodsSerializer, MyGoodsSer
from utils.Alipay import AliPaySDK


# Create your views here.

class OrderView(APIView):
    def post(self, request):
        user = request.data.get('user')
        status = request.data.get('status')
        cart = CartModel.objects.filter(user=user, select=True)
        all_price = 0
        for i in cart:
            all_price += i.goods.g_price * i.c_num
        order_data = {
            "user": user,
            "total_price": all_price,
            "status": status,
            "order_no": time.strftime("%Y%m%d%H%M%S", time.localtime()),
        }
        order_ser = OrderSerializer(data=order_data)
        if order_ser.is_valid():
            order_ser.save()
            for i in cart:
                detail_data = {
                    'order': order_ser.data['id'],
                    'goods': i.goods.id,
                    'g_name': i.goods.g_name,
                    'number': i.c_num,
                    'price': i.goods.g_price,
                    'g_img': 'http://127.0.0.1:8000/uploads/' + str(i.goods.g_img),
                }
                detail_ser = DetailSerializer(data=detail_data)
                if detail_ser.is_valid():
                    detail_ser.save()
                    i.delete()
                else:
                    return Response(detail_ser.errors)
        ail = AliPaySDK()
        return Response({'pay': ail.page_pay(order_data.get('order_no'), order_data.get('total_price'), '商品付款'),
                         "order_no": order_data.get('order_no')})


class MyGoodsView(APIView):
    def get(self, request):
        user = request.query_params.get('user')
        order_no = request.query_params.get('order_no')
        address = request.query_params.get('address')
        order = OrderModel.objects.filter(user=user, order_no=order_no).first()
        detail = DetailModel.objects.filter(order=order.id)
        for i in detail:
            my_data = {
                'user': user,
                'goods': i.goods.id,
                'address': address,
                'g_name': i.goods.g_name,
                'number': i.number,
                'price': i.goods.g_price * i.number,
                'g_img': 'http://127.0.0.1:8000/uploads/' + str(i.goods.g_img),
                'status': i.order.status,
            }
            my_ser = MyGoodsSerializer(data=my_data)
            if my_ser.is_valid():
                my_ser.save()
                return Response({"code": 200, "message": "支付成功", })
            else:
                return Response(my_ser.errors)


class Pagination(PageNumberPagination):
    page_size = 1
    page_size_query_param = 'size'
    page_query_param = 'page'


class MyGoodsList(ListAPIView):
    queryset = MyGoodsModel.objects.all()
    serializer_class = MyGoodsSer
    pagination_class = Pagination

    def get_queryset(self):
        query = Q()
        user = self.request.query_params.get('user')
        status = self.request.query_params.get('status')
        if user:
            query &= Q(user=user)
        if int(status) > 0:
            query &= Q(status=status)
        return MyGoodsModel.objects.filter(query)
